var modellist = {
	app001: "商家拓展",
	app002: "接收派工",
	app003: "设备实发",
	app004: "设备签收",
	app005: "施工完成",
	app006: "施工验收",
	app007: "拆机派工",
	//app008 : "拆机完成",
	//app009 : "拆机验收",
	app010: "拆机实收",
	app011: "维修派工",
	app012: "维修完成",
	app013: "维修验收",
	app014: "设备入库",
	app015: "设备出库",
	app016: "设备盘点",
	//app051: "拓展查看",
	app051: "现场勘察"
};
var msgTypeList = ["系统通知", "拓展驳回", "施工整改", "拓展暂存"];
var appUpDateUrl = summer.getStorage("serverAdress") + "/Axis2Api/AppVersion";
//服务器地址
var adressHead = {
	ISjtzImpl: {
		wsConfig: {
			wsName: "ISjtzImpl",
			nameSpace: "http://jk.dftc.itf.nc/ISjtzImpl"
		}
	},
	ISjtzImpl2: {
		wsConfig: {
			wsName: "ISjtzImpl2",
			nameSpace: "http://jk.dftc.itf.nc/ISjtzImpl2"
		}
	},
	IUserService: {
		wsConfig: {
			wsName: "IUserService",
			nameSpace: "http://jk.dftc.itf.nc/IUserService"
		}
	},
	IInstallationImpl: {
		wsConfig: {
			wsName: "IInstallationImpl",
			nameSpace: "http://jk.dftc.itf.nc/IInstallationImpl"
		}
	},
	IInstallationImpl2: {
		wsConfig: {
			wsName: "IInstallationImpl2",
			nameSpace: "http://jk.dftc.itf.nc/IInstallationImpl2"
		}
	},
	IDisassembleImpl: {
		wsConfig: {
			wsName: "IDisassembleImpl",
			nameSpace: "http://jk.dftc.itf.nc/IDisassembleImpl"
		}
	},
	IMaintenanceImpl: {
		wsConfig: {
			wsName: "IMaintenanceImpl",
			nameSpace: "http://jk.dftc.itf.nc/IMaintenanceImpl"
		}
	},
	IAzpgDwkcImpl2:{
		wsConfig: {
			wsName: "IAzpgDwkcImpl2",
			nameSpace: "http://jk.dftc.itf.nc/IAzpgDwkcImpl2"
		}
	
	}
	

};

var writeUploadimg = [];
var postParas;
var endFun;
function uploadImg(){
	changeLoadingTitle("正在上传图片,剩余" + writeUploadimg.length + "张");
	var a = writeUploadimg.shift();
	if(!a){
		endFun();
		return;
	}
	summer.upload({
			fileURL: a.urls,
			type: "image/jpeg",
			//params:{},
			SERVER:summer.getStorage("serverAdress").replace("%EF%BC%9A",":").replace("：",":").replace("%00","")  + "/service/photoinsert"
		}, function(ret) {
			document.getElementById(a.id).src = getImgUrl(ret.response);
			imgs[a.id] = ret.response;
			eval("postParas.dataParm."+ a.id +" = ret.response;");
			setTimeout(function() {
				uploadImg();
			},100);
		}, function(err) {
			changeLoadingTitle();
			alerts("上传图片时出错,请稍后重试:" + JSON.stringify(err));
			return;
	});
}
//上传图片
function doPost(wsName, wsmethod, para, successFun, errorFun, hideDoing) {
	var havaimg = false;
	writeUploadimg = [];
	for(var i in para.dataParm){
		if(i=="remove" || i=="remove2" || i=="null" || i=="remove3" || i=="insert"){
				continue;
		}
		if(para.dataParm[i] && (para.dataParm[i].toString().indexOf("/") == 0 ||para.dataParm[i].toString().indexOf("file") == 0 || para.dataParm[i].toString().indexOf("UAPTEMP") != -1)){
			havaimg = true;
			writeUploadimg.push({
				id:i,
				urls:para.dataParm[i].replace("file://","")
			}); 
		}
	}
	if(havaimg){
		postParas = para;
		endFun = function(){
			doPost2(wsName, wsmethod, postParas, successFun, errorFun, hideDoing);
		};
		uploadImg();
	}else{
		doPost2(wsName, wsmethod, para, successFun, errorFun, hideDoing);
	}
}
//服务器地址，取图片地址
function getImgUrl(url){
	if (url) {
		if (url.indexOf("/") == 0 || url.indexOf("file") == 0) {
			return url;
		} else {
			return summer.getStorage("serverAdress") + "/service/photoquery?path=" + url;
		}
	}
	return "";
}
//发送post请求
//webservices地址，方法名，json参数，成功方法，失败方法，是否隐藏加载框
function doPost2(wsName, wsmethod, para, successFun, errorFun, hideDoing) {
	var adress = summer.getStorage("serverAdress");
	try {
		if(!hideDoing) {
			changeLoadingTitle("请稍等");
		}
		if(!errorFun) {
			errorFun = function(e) {
				changeLoadingTitle();
				alerts(e);
			}
		}
		wsName.method = wsmethod;
		para = $.extend({}, para, wsName);
		$.ajax({
			//timeout: 120000, //超时时间设置100秒
			type: 'POST',
			url: adress + "/Axis2Api/WsRequest",
			data: {//清除所有空格
				"data": JSON.stringify(para) //.replace(/ /g,"")    //时间有空格
			},
			success: function(response) {
				try {
					if(!hideDoing) {
						changeLoadingTitle();
					}
					var data = JSON.parse(response);
					if(data.result) {
						successFun(data.data);
					} else {
						UM.hideLoadingBar();
						errorFun("服务器返回异常");
					}
				} catch(e) {
					errorFun("获取时出现异常:" + e + JSON.stringify(response));
				}
			},
			error: function(e) {
				if(!hideDoing) {
					changeLoadingTitle();
				}
				errorFun("(╥﹏╥) 连接失败了 请改善网络或稍后再试..." + JSON.stringify(e));
			},
		});
	} catch(e) {
		if(!hideDoing) {
			changeLoadingTitle();
		}
		errorFun(e);
	}
}

function init() {
	//.back 退出当前窗体
	var imgList = document.querySelectorAll(".back");
	for(var len = imgList.length,
			i = 0; i < len; i++) {
		imgList[i].addEventListener("click", function(d) {
			summer.closeWin();
		}, false);
	}
	//.lookimg 退出当前窗体
	var imgList = document.querySelectorAll(".lookimg");
	for(var len = imgList.length, i = 0; i < len; i++) {
		imgList[i].addEventListener("click", function(event) {
			event.stopPropagation();
			summer.openWin({
				id: "lookphoto",
				url: "html/all/LookPhoto.html",
				isKeep: true,
				reload: true,
				pageParam: {
					data: this.src
				}
			});
		}, false);
	}
};



function IOSimgLook(obj) {
	summer.openWin({
		id: "lookphoto",
		url: "html/all/LookPhoto.html",
		isKeep: true,
		reload: true,
		pageParam: {
			data: obj.src
		}
	});
}

$(".camera").load(function() {
	if(this.src.indexOf("camera.png") == -1) {
		if($(".img_" + this.id).length == 0) {
			$("#" + this.id).attr("onclick", "IOSimgLook(this)");
			$("#" + this.id).before("<span class='img_" + this.id + "'><a onclick=\"deleteImg(document.getElementById('" + this.id + "'))\">清除</a>&nbsp;&nbsp;<a onclick=\"openCamera(document.getElementById('" + this.id + "'),pageid)\">重拍</a>&nbsp;&nbsp;<a onclick=\"rotate(document.getElementById('" + this.id + "'),pageid)\">旋转</a>&nbsp;&nbsp;</span>");
			
		}
	} else {
		$("#" + this.id).attr("onclick", "openCamera(this,pageid)");
		$(".img_" + this.id).remove();
	}
});

//清除图像
function deleteImg(obj){
	document.getElementById(obj.id).src = "../../img/myimg/camera.png";
	imgs[obj.id] = null;
}
//相机打开 返回图像位置

var imgs = [];
function openCamera(obj, pageID) {
	try {
		summer.openCamera({
			cameraType:"custom",
			callback: function(args) {
				if(!summer.getStorage("adressPaiZhao")){
					var filepath = args.imgPath.substr(0, args.imgPath.lastIndexOf("/")) + "/";
					summer.setStorage("adressPaiZhao",filepath);
				}
				if(summer.getSysInfo().systemType == "android") {
					try {
							summer.callService("UMFile.compressImg", { //compressImgInThread
								"src": args.imgPath,
								"path": args.imgPath,
								"compressWidth": "1000",
								"compressHeight": "1000",
								"quality": "0.8",
								"callback": function(arg) {
									if(!summer.getStorage("adressYaSuo")){
										var filepath = arg.savepath.substr(0, arg.savepath.lastIndexOf("/")) + "/";
										summer.setStorage("adressYaSuo",filepath);
									}
									summer.setAppStorage("pageParamImageBase64", JSON.stringify({
											id: obj.id, //编号
											base64: arg.savepath, //url
											pageId: pageID //page ID
										}));
										rotateBack();
								}
							}, false);
					} catch(e) {
						alerts("压缩图像时出错了" + e);
					}
				} else {
					try {
							summer.callService("UMFile.compressImg", { //compressImg
								"src": args.imgPath,
								"path": args.imgPath,
								"compressWidth": "1000",
								"compressHeight": "1000",
								"quality": "0.7",
								"callback": function(arg) {
									if(!summer.getStorage("adressYaSuo")){
										var filepath = arg.path.substr(0, arg.path.lastIndexOf("/")) + "/";
										summer.setStorage("adressYaSuo",filepath);
									}
									summer.setAppStorage("pageParamImageBase64", JSON.stringify({
											id: obj.id, //编号
											base64: arg.path, //url
											pageId: pageID //page ID
										}));
										rotateBack();
								}
							}, false);
					} catch(e) {
						alerts("压缩图像时出错了" + e);
					}
				}
			}
		});
	} catch(e) {
		alerts(e);
	}
}

function rotate(obj, pageID) {
	summer.openWin({
		id: "rotateImg",
		url: "html/all/rotateImg.html",
		isKeep: true,
		pageParam: {
			id: obj.id, //编号
			base64: obj.src, //url
			pageId: pageID //page ID
		}
	});
}
//旋转页面的回调函数
function rotateBack() {
	try {
		var obj = JSON.parse(summer.getAppStorage("pageParamImageBase64"));
		summer.setAppStorage("pageParamImageBase64", "");
		document.getElementById(obj.id).src = obj.base64;
		imgs[obj.id] = obj.base64;
	} catch(e) {
		alerts("旋转回调错误:" + e);
	}
}

//将图片转成base64   Noya(number类型)压缩比例0-1
function getBase64Image(url, backfun, Noya) {
	var base64 = summer.fileToBase64({
		"filePath": url
	});
	backfun("data:image/jpeg;base64," + base64);
}
function filetobase64(urls){
	var aa = summer.fileToBase64({
		"filePath": urls.replace("file://","")
	});
	return ("data:image/jpeg;base64," + aa);
}
function base64Tofile(base64){
	var timestamp = "/storage/emulated/0/Download/"+ Date.parse(new Date()) +".jpg";
	var base2 = summer.base64ToFile({
			"base64" : base64.replace("data:image/jpeg;base64,",""),
		    "filePath": timestamp 
		});

		if(base2){
			return timestamp;
		}else{
			return base64;
		}
}
function imgsbm(){
	try{
		for(var a in imgs){
			if(a=="remove" || a=="remove2" || a=="null" || a=="remove3" || a=="insert"){
				continue;
			}
			if(imgs[a] && imgs[a].length<200){
				imgs[a] = filetobase64(imgs[a]);
			}
		}
	}catch(e){
		alert(e);
	}
}


//验证是否拥此权限
function getPermissions(self) {
	var permssion = summer.getStorage('userinfo').rolePermissions;
	var array = permssion.split(",");
	if(permssion.toString().indexOf(self) > -1)
		return true;
	//存在
	else
		return false;
	//不存在
}

function toasts(val, title) {
	UM.toast({
		title: (!!!title) ? "系统提示：" : title,
		text: val,
		duration: 2000
	});
}

//显示或隐藏loading ，title-显示的中文，不传就隐藏loading
function changeLoadingTitle(title){
	if(title){
		if($(".um-modal.um-modal-in").length == 0){ //没有loading
			UM.showLoadingBar({
				text: title,
				icons: 'ti-reload',
			});
		}else{
			$(".um-modal.um-modal-in").children("div").text(title);
		}
	}else{
		setTimeout(function() {
			if($(".um-modal.um-modal-in").length != 0){ //没有loading
				$(".um-overlay").remove();
				$(".um-modal.um-modal-in").remove();
				UM.hideLoadingBar();
			}
		},100);
	}
}

function alerts(val,back) {
	UM.alert({
		title: val,
		btnText: ["取消", "确定"],
		overlay: true,
		ok: function() {
			if(back){
				back();
			}
		}
	});
}

var loginDate;
function MessageJunp(jsons) {
	//	{
	//		context: "", //通知内容
	//		messageId: "", //通知编号
	//		thistime: "", //通知时间
	//		type: "", //通知类型
	//	}
	var openWinid,
		openWinurl;
	//编号
	switch(Number(jsons.type)) {
		case 0:
			break;
		case 1://系统消息
			alerts(jsons.context);
			break;
		case 2:
			openWinid = "shangjiatuozhan";
			openWinurl = "html/ShangJiaCaiJi/insert.html";
			break;
		case 4:
			openWinid = "shangjiatuozhan";
			openWinurl = "html/ShangJiaCaiJi/insert.html";
			break;
		case 100://挤下线
			if(!loginDate){return;}
			if(loginDate < new Date(jsons.context)){
				return;
			}
			alerts("你的账户已在别处登录,如有疑问,请修改密码后重试!",function(){
				summer.exitApp();
			});
			break;
	}
	if(openWinid) {
		summer.openWin({
			id: openWinid,
			url: openWinurl,
			isKeep: true,
			pageParam: jsons,
			reload: true
		});
	}
}

var format = function(time, format) {
	var t = new Date(time);
	var tf = function(i) {
		return(i < 10 ? '0' : '') + i
	};
	return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
		switch(a) {
			case 'yyyy':
				return tf(t.getFullYear());
				break;
			case 'MM':
				return tf(t.getMonth() + 1);
				break;
			case 'mm':
				return tf(t.getMinutes());
				break;
			case 'dd':
				return tf(t.getDate());
				break;
			case 'HH':
				return tf(t.getHours());
				break;
			case 'ss':
				return tf(t.getSeconds());
				break;
		}
	});
}
/**
 * 整数校验
 * @param {Object} s
 */
function isDigit(s) {
	var patrn = /^[1-9]\d*$/;
	if(!patrn.exec(s))
		return false
	return true
}

/**
 *   验证字符串是否是数字
 * @param {Object} theObj
 */
function checkNumber(theObj) {
	var reg = /^[0-9]+.?[0-9]*$/;
	if(reg.test(theObj)) {
		return true;
	}
	return false;
}

function isMacAdress(mac){
	var macs = new Array();
		macs = mac.split(":");
		if(macs.length != 6) {
			return false;
		}
		for(var s = 0; s < 6; s++) {
			var temp = parseInt(macs[s], 16);

			if(isNaN(temp)) {
				return false;
			}
			if(temp < 0 || temp > 255) {
				return false;
			}
		}
		return true;
}
function isEns(str){
	var len = str.length;
	if(len!= 14 && len!= 20){
		return false;
	}
	return true;
}
/**
 *   验证字符串是否是电话号码
 * @param {Object} theObj
 */
function checkMobile(str) {
	var re = /^1\d{10}$/;
	var re2 = /^0\d{2,3}-?\d{7,8}$/;
	if(re.test(str) || re2.test(str)) {
		return true;
	} else {
		return false;
	}
}

/**
 * 星标排序
 * @param {Object} array
 * @param {Object} key
 */
function sortByKey(array, key) {
	return array.sort(function(a, b) {
		var x = a[key];
		var y = b[key];
		return((x < y) ? -1 : ((x > y) ? 1 : 0));
	}).reverse();
}

init();